<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" width="600px" @close="close">
    <el-form ref="form" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="房产名称" prop="propertyName">
        <el-select v-model="form.propertyId" placeholder="请选择房产名称" :disabled="isDisabled">
          <el-option v-for="option in propertyList" :key="option.value" :label="option.label" :value="option.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="房东姓名" prop="ownerName">
        <el-input v-model.trim="form.ownerName" autocomplete="off" :disabled="isDisabled" />
      </el-form-item>
      <el-form-item label="房东电话" prop="ownerPhone">
        <el-input v-model.trim="form.ownerPhone" autocomplete="off" :disabled="isDisabled" />
      </el-form-item>
      <el-form-item label="整套面积" prop="houseArea">
        <el-input v-model.trim="form.houseArea" autocomplete="off" />
      </el-form-item>
      <el-form-item label="押金" prop="cashPledge">
        <el-input v-model.trim="form.cashPledge" autocomplete="off" />
      </el-form-item>
      <el-form-item label="楼层" prop="floor">
        <el-input v-model.trim="form.floor" autocomplete="off" />
      </el-form-item>
      <el-form-item label="楼房类型" prop="stepType">
        <el-input v-model.trim="form.stepType" autocomplete="off" />
      </el-form-item>
      <el-form-item label="起租日期" prop="startDate">
        <el-input v-model.trim="form.startDate" autocomplete="off" />
      </el-form-item>
      <el-form-item label="到租日期" prop="endDate">
        <el-input v-model.trim="form.endDate" autocomplete="off" />
      </el-form-item>
      <el-form-item label="总楼层" prop="allFloor">
        <el-input v-model.trim="form.allFloor" autocomplete="off" />
      </el-form-item>
      <el-form-item label="房牌号" prop="houseNo">
        <el-input v-model.trim="form.houseNo" autocomplete="off" />
      </el-form-item>
      <el-form-item label="房间特色" prop="featureIds">
        <div>
          <div v-for="(group, type) in groupedFeatures" :key="type">
            <!-- 根据 type 显示对应的大标题 -->
            {{ getGroupTitle(type) }}
            <!-- 显示特色复选框列表 -->
            <el-checkbox-group v-model="form.featureIds">
              <el-checkbox v-for="feature in group" :key="feature.id" :label="feature.id">
                {{ feature.feature }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="出租类型" prop="type">
        <el-radio-group v-model="form.type">
          <el-radio :label="0">月租</el-radio>
          <el-radio :label="1">季租</el-radio>
          <el-radio :label="2">半年租</el-radio>
          <el-radio :label="3">年租</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="出租状态" prop="state">
        <el-radio-group v-model="form.state">
          <el-radio :label="0">待出租</el-radio>
          <el-radio :label="1">出租中</el-radio>
          <el-radio :label="2">已出租</el-radio>
          <el-radio :label="3">已下架</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { doEdit } from '@/api/house/room'
  import { getList } from '@/api/house/property'
  import { getFeatureList } from '@/api/house/feature'

  export default {
    name: 'UserManagementEdit',
    data() {
      return {
        form: {
          typetype: '',
          state: '',
          houseArea: '',
          cashPledge: '',
          floor: '',
          stepType: '',
          startDate: '',
          endDate: '',
          ownerName: '',
          ownerPhone: '',
          propertyId: '',
          propertyName: '',
          allFloor: '',
          houseNo: '',
          ownerName: '',
          featureIds: []
        },
        rules: {
          propertyId: [{ required: true, trigger: 'blur', message: '请选择房产' }],
          password: [{ required: true, trigger: 'blur', message: '请输入密码' }],
          email: [{ required: true, trigger: 'blur', message: '请输入邮箱' }],
          permissions: [{ required: true, trigger: 'blur', message: '请选择权限' }],
        },
        title: '',
        dialogFormVisible: false,
        propertyList: [],
        featureList: [],
        disabled: false,
        allFeatures: [], // 所有从后端返回的特色列表
        selectedFeatures: {}, // 用于存储选中的特色
      }
    },
    created() {
      // 组件加载时获取数据
      this.fetchPropertyOptions()
      this.fetchFeatureOptions()
    },
    methods: {
      showEdit(row) {
        if (!row) {
          this.title = '添加'
          this.disabled = false
        } else {
          this.title = '编辑'
          this.form = Object.assign({}, row)
          this.disabled = true
        }
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            const { msg } = await doEdit(this.form)
            this.$baseMessage(msg, 'success')
            this.$emit('fetch-data')
            this.close()
          } else {
            return false
          }
        })
      },
      async fetchPropertyOptions() {
        try {
          const response = await getList({ pageSize: 100 }) // 假设接口返回房产名称数据
          this.propertyList = response.data.list.map((item) => ({
            label: item.name,
            value: item.id,
          }))
        } catch (error) {
          console.error('Failed to fetch property names', error)
        }
      },
      async fetchFeatureOptions() {
        try {
          const response = await getFeatureList() // 假设接口返回房产名称数据
          console.log('response', response)
          this.allFeatures = response.data.map((item) => ({
            label: item.feature,
            id: item.id,
            type: item.type,
          }))
        } catch (error) {
          console.error('Failed to fetch property names', error)
        }
        // 初始化 selectedFeatures 对象，确保每种 type 都有一个空数组以存储选中的特色
        Object.keys(this.groupedFeatures).forEach((type) => {
          this.selectedFeatures[type] = []
        })
      },
      getGroupTitle(type) {
        // 根据 type 返回对应的标题
        // 这里假设需要根据每个 type 动态显示不同的标题
        if (type === '0') {
          return '房间配置'
        } else if (type === '1') {
          return '居住要求'
        } else if (type === '2') {
          return '亮点'
        }
      },
    },
    computed: {
      isDisabled() {
        // 根据密码字段是否有值来决定是否禁用输入框
        return this.disabled // 如果有值，则禁用输入框
      },
      groupedFeatures() {
        // 根据 type 分组特色数据
        const grouped = {}
        this.allFeatures.forEach((feature) => {
          if (!grouped[feature.type]) {
            grouped[feature.type] = []
          }
          grouped[feature.type].push({
            id: feature.id,
            feature: feature.label, // 确认使用正确的属性名
            type: feature.type,
          })
        })
        return grouped
      },
    },
  }
</script>
